/*
 * www.unisinsight.com Inc.
 * Copyright (c) 2019 All Rights Reserved.
 */
package com.fengwuj.mutils.reflect;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 修订记录：
 * jiangbo 2020/3/24 9:57 创建
 *
 * @author jiangbo
 */
@Slf4j
public class ReflectUtils {
    private static final char LOWER_CHAR_START = 'a';
    private static final char LOWER_CHAR_END = 'z';
    private static final int IV = 32;
    private static final String GET_NAME_STR = "get";
    private static final String SET_NAME_STR = "set";

    /**
     * 获取该类的属性
     * @param clazz 被获取属性的类
     * @return
     */
    public static List<String> getClassProperties(Class<?> clazz){
        return Arrays.stream(clazz.getDeclaredFields()).map(Field::getName).collect(Collectors.toList());
    }

    /**
     * 通过属性名获取实体值
     * @param model
     * @param property
     * @return
     */
    public static Object getValueByProperty(Object model,String property){
        String getMethordName = GET_NAME_STR + upperCase(property);
        Object result = null;
        try {
            Method getMethord = model.getClass().getMethod(getMethordName);
            result = getMethord.invoke(model);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    public static void setValueByProperty(Object model,String property,Object value){
        //找到get方法
        String getMethordName = GET_NAME_STR + upperCase(property);
        String setMethordName = SET_NAME_STR + upperCase(property);
        Class<?> clazz = model.getClass();
        try {
            Method getMethord = clazz.getMethod(getMethordName);
            //找到set方法
            Method setMethord = clazz.getMethod(setMethordName,getMethord.getReturnType());
            setMethord.invoke(model,value);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 首字母大写
     * @param str
     * @return
     */
    public static String upperCase(String str){
        char[] ch = str.toCharArray();
        if (ch[0] >= LOWER_CHAR_START && ch[0] <= LOWER_CHAR_END){
            ch[0] = (char)(ch[0] - IV);
        }
        return new String(ch);
    }
}
